//
//  BGRecordDetailViewController.swift
//  Billing
//
//  Created by Dale on 17/4/24.
//  Copyright © 2017年 Nari. All rights reserved.
//

import UIKit

class BGRecordDetailViewController: BCFatherViewController, UITableViewDelegate, UITableViewDataSource {
    lazy var tableView: UITableView = {
        let tempTableView = UITableView (frame: self.view.bounds, style: UITableViewStyle.plain)
        tempTableView.delegate = self
        tempTableView.dataSource = self
        tempTableView.separatorStyle = .none
        return tempTableView
    }()
    var commitBtn: UIButton!
    
    var record: Rocord!
    var tmpMoney: String?
    var dataSource = [Model]()
    var srcDataSource = [Model]()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        title = "修改账单"
        tmpMoney = record.money
        print("rocord:\(record)")
        self.view.addSubview(tableView)
        customBackBarItem()
        let model = Model(title: "日期", detail: (record?.dateStamp!)!, type: 0)
        dataSource.append(model)
        let model1 = Model(title: "时间", detail: (record?.timeStamp!)!, type: 0)
        dataSource.append(model1)
        
        var str: String?
        switch record.type {
        case "0"?:
            str = "早上"
        case "1"?:
            str = "中午"
        case "2"?:
            str = "晚上"
        default:
            str = "其它"
        }
        
        let model2 = Model(title: "类型", detail: str!, type: 0)
        dataSource.append(model2)
        let model3 = Model(title: "金额", detail: (record?.money!)!, type: 1)
        dataSource.append(model3)
        let model4 = Model(title: "", detail: "", type: 2)
        dataSource.append(model4)
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //赋值为原来的
        srcDataSource.removeAll()
        for item in dataSource {
            let model = Model(title: "", detail: "", type:0)
            model.detail = item.detail
            model.title = item.title
            model.type = item.type
            srcDataSource.append(model)
        }
        commitBtn.isEnabled = false
        commitBtn.backgroundColor = .gray
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = dataSource[indexPath.row]
        let cell = BGSubmitCell.cellWithTableView(tableView: tableView, obj: model)
        cell.configureCell(model: model)
        commitBtn = cell.submitBtn
        if tmpMoney != nil {
            cell.textField?.text = tmpMoney!
        }
        cell.clickClosure = { (money: String, type: Int)-> Void in
            if type == 1 {
                self.modifyAction()
            } else {
                self.tmpMoney = money
                let model = self.srcDataSource[3]
                model.detail = money
                if self.isSameWithOld(src: self.srcDataSource, des: self.dataSource) {
                    self.commitBtn.backgroundColor = .gray
                    self.commitBtn.isEnabled = false
                } else {
                    self.commitBtn.backgroundColor = UIColor(hex: "1cca93")
                    self.commitBtn.isEnabled = true
                }
            }
        }
        if(indexPath.row == 4 && indexPath.section == 0) {
            cell.selectionStyle = .none
        }
        return cell
    }
    
    func modifyAction () -> Void {
        view.endEditing(true)
        if tmpMoney == nil {
            SVProgressHUD.showError(withStatus: "请输入金额")
            return
        }
        
        if tmpMoney == "0" || tmpMoney == "" {
            SVProgressHUD.showError(withStatus: "请输入金额")
            return
        }
        
        if !AssistClass.isPureFloat(self.tmpMoney) {
            SVProgressHUD.showError(withStatus: "请输入纯数字")
            return
        }
        
        let num = NSString(string: self.tmpMoney!).floatValue
        let tmpStr = "\(num)"
        print(num)
        
        if !AssistClass.isValid(tmpStr) {
            SVProgressHUD.showError(withStatus: "最多输入两位小数")
            return
        }
        
        if num < 0.0 {
            SVProgressHUD.showError(withStatus: "请输入大于0的数字")
            return
        }
        
        if num > 1000.0 {
            SVProgressHUD.showError(withStatus: "请输入小于1000的数字")
            return
        }
        
        
        let rocord = Rocord()
        rocord.dateStamp = dataSource[0].detail!
        rocord.timeStamp = dataSource[1].detail!
        rocord.type = dataSource[2].detail!
        rocord.money = tmpStr
        rocord.objectId = self.record.objectId
        
        
        
        if Common.getCurrentDate() == dataSource[0].detail! {
            let selectStr = dataSource[1].detail!.replacingOccurrences(of: ":", with: ".")
            let timeStr = Common.getCurrentTime().replacingOccurrences(of: ":", with: ".")
            let selectTime = NSString(string: selectStr).floatValue
            let time = NSString(string: timeStr).floatValue
            if selectTime > time {
                SVProgressHUD.showError(withStatus: "请选择小于当前系统时间")
                return
            }
        }
        
        
        var type: NSNumber?
        switch rocord.type {
        case "早上"?:
            type = NSNumber(value: 0)
        case "中午"?:
            type = NSNumber(value: 1)
        case "晚上"?:
            type = NSNumber(value: 2)
        default:
            type = NSNumber(value: 3)
        }
        let tmpType = type?.stringValue
        
        SVProgressHUD.show()
        
        self.commitBtn.backgroundColor = .gray
        self.commitBtn.isEnabled = false
        
        if rocord.dateStamp != self.record.dateStamp ||  tmpType != self.record.type {
            BmobManager.queryOneRecord(dateStamp: rocord.dateStamp!, type: type!) { (result, status) -> (Void) in
                if status == .NRSSuccess {
                    BmobManager.modifyRecord(rocord, type!) { (result, status) -> (Void) in
                        SVProgressHUD.dismiss(withDelay: 1.0, completion: {
                            if status == .NRSSuccess {
                                SVProgressHUD.showSuccess(withStatus: result as! String!)
                                isRefrsh = true
                                self.navigationController?.popViewController(animated: true)
                            } else {
                                SVProgressHUD.showError(withStatus: result as! String)
                            }
                        })
                    }
                } else {
                    SVProgressHUD.showError(withStatus: result as! String)
                    self.commitBtn.backgroundColor = UIColor(hex: "1cca93")
                    self.commitBtn.isEnabled = true
                }
                
            }
        } else {
            BmobManager.modifyRecord(rocord, type!, result: { (res, status) -> (Void) in
                    if status == .NRSSuccess {
                        SVProgressHUD.showSuccess(withStatus: "提交成功")
                        isRefrsh = true
                        SVProgressHUD.dismiss(withDelay: 1.0) {
                           self.navigationController?.popViewController(animated: true)
                        }
                       
                    } else {
                        SVProgressHUD.showError(withStatus: res as! String)
                        self.commitBtn.backgroundColor = UIColor(hex: "1cca93")
                        self.commitBtn.isEnabled = true
                    }
            })
        }
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        view.endEditing(true)
        let model = dataSource[indexPath.row]
        if indexPath.row == 0 {
            let customAlert = Bundle.main.loadNibNamed("CustomAlertView", owner: nil, options: nil)?[0] as! CustomAlterView
            let locale = NSLocale(localeIdentifier: "zh_CN")
            customAlert.datePicker?.locale = locale as Locale
            customAlert.datePicker?.maximumDate = NSDate() as Date
            customAlert.datePicker.datePickerMode = .date
            customAlert.datePickerType = DatePickerType(rawValue: 0)
            customAlert.cellType = 0
            customAlert.typeClosure = { (str: String)-> Void in
                model.detail = str
                self.tableView.reloadData()
                if self.isSameWithOld(src: self.srcDataSource, des: self.dataSource) {
                    self.commitBtn.backgroundColor = .gray
                    self.commitBtn.isEnabled = false
                } else {
                    self.commitBtn.backgroundColor = UIColor(hex: "1cca93")
                    self.commitBtn.isEnabled = true
                }
            }
            customAlert.showAlertView()
        }
        if indexPath.row == 1 {
            let customAlert = Bundle.main.loadNibNamed("CustomAlertView", owner: nil, options: nil)?[0] as! CustomAlterView
            let locale = NSLocale(localeIdentifier: "da_DK")
            customAlert.datePicker?.locale = locale as Locale
            customAlert.datePicker.datePickerMode = .time
            customAlert.datePickerType = DatePickerType(rawValue: 1)
            customAlert.cellType = 0
            customAlert.typeClosure = { (str: String)-> Void in
                model.detail = str
                let type = Common.configureType(type: str)
                (self.dataSource[2] as Model).detail = type
                self.tableView.reloadData()
                if self.isSameWithOld(src: self.srcDataSource, des: self.dataSource) {
                    self.commitBtn.backgroundColor = .gray
                    self.commitBtn.isEnabled = false
                } else {
                    self.commitBtn.backgroundColor = UIColor(hex: "1cca93")
                    self.commitBtn.isEnabled = true
                }
            }
            let dateformatter = DateFormatter()
            dateformatter.dateFormat = "yyyy-MM-dd"
            let dateString = dateformatter.string(from: Date())
            if(dataSource[0].detail == dateString) {
                //等于今天
                customAlert.datePicker?.maximumDate = NSDate() as Date
            }
            customAlert.showAlertView()
        }
        if indexPath.row == 2 {
            let customAlert = Bundle.main.loadNibNamed("CustomAlertView", owner: nil, options: nil)?[1] as! CustomAlterView
            customAlert.cellType = 0
            customAlert.tmpType = model.detail
            customAlert.typeClosure = { (str: String)-> Void in
                model.detail = str
                self.tableView.reloadData()
                if self.isSameWithOld(src: self.srcDataSource, des: self.dataSource) {
                    self.commitBtn.backgroundColor = .gray
                    self.commitBtn.isEnabled = false
                } else {
                    self.commitBtn.backgroundColor = UIColor(hex: "1cca93")
                    self.commitBtn.isEnabled = true
                }
            }
            customAlert.showAlertView()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 4 {
            return 100
        }
        return 60
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
    
    func isSameWithOld(src:[Model], des:[Model]) -> Bool {
        var isSame = true
        for i in 0..<src.count {
            let srcItem:Model = src[i]
            let desItem:Model = des[i]
            if srcItem.detail != desItem.detail {
                isSame = false
            }
        }
        return isSame
    }
}
